import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import TensorDataset
from torch.utils.data import Dataset
from torch.utils.data import DataLoader
import torch
import torchvision

import matplotlib.image as mpimg
import matplotlib.pyplot as plt
import json
import torch.optim as optim

n_epochs = 3
# 批数据量
batch_size_train = 100
batch_size_test = 1000

# lr
learning_rate = 0.01
momentum = 0.5

DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
log_interval = 10
random_seed = 1

# 训练批次
EPOCHS = 20
torch.manual_seed(random_seed)


class CNN(nn.Module):
    def __init__(self):
        super(CNN, self).__init__()
        # torch.Size([100, 1, 28, 28])
        # 深度10 (W-F+2P)/S + 1
        self.conv1 = nn.Conv2d(1, 10, kernel_size=5, padding=2, stride=1)  # 1 * 10 * 28 * 28
        self.conv2 = nn.Conv2d(10, 20, kernel_size=3, padding=1, stride=1)  # 10*20*28*28

        self.fc1 = nn.Linear(20*28*28 ,500)
        self.fc2 = nn.Linear(500, 10)

    def forward(self, x):
        size = x.size(0)
        x = F.relu(self.conv1(x))
        x = F.relu(self.conv2(x))
        x = x.view(size,-1)
        x = self.fc1(x)
        x = self.fc2(x)

        x = F.log_softmax(x, dim=1)
        return x
    # def __init__(self):
    #     super().__init__()
    #     # 1*1*28*28
    #     self.conv1 = nn.Conv2d(1, 10, 5)
    #     self.conv2 = nn.Conv2d(10, 20, 3)
    #     self.fc1 = nn.Linear(20 * 10 * 10, 500)
    #     self.fc2 = nn.Linear(500, 10)
    #
    # def forward(self, x):
    #     in_size = x.size(0)
    #     out = self.conv1(x)  # 1* 10 * 24 *24
    #     out = F.relu(out)
    #     out = F.max_pool2d(out, 2, 2)  # 1* 10 * 12 * 12
    #     out = self.conv2(out)  # 1* 20 * 10 * 10
    #     out = F.relu(out)
    #     out = out.view(in_size, -1)  # 1 * 2000
    #     out = self.fc1(out)  # 1 * 500
    #     out = F.relu(out)
    #     out = self.fc2(out)  # 1 * 10
    #     out = F.log_softmax(out, dim=1)
    #     return out


def train(model, device, train_loader, optimizer, epoch):
    print("开始训练")
    model.train()
    for batch_idx, (data, target) in enumerate(train_loader):
        data, target = data.to(device), target.to(device)

        optimizer.zero_grad()
        output = model(data)
        loss = F.cross_entropy(output, target)
        loss.backward()
        optimizer.step()
        if (batch_idx + 1) % 30 == 0:
            print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format(
                epoch, batch_idx * len(data), len(train_loader.dataset),
                       100. * batch_idx / len(train_loader), loss.item()))


# 定义测试函数
def test(model, device, test_loader):
    model.eval()
    test_loss = 0
    correct = 0
    with torch.no_grad():
        for data, target in test_loader:
            data, target = data.to(device), target.to(device)
            output = model(data)

            test_loss += F.nll_loss(output, target, reduction='sum')  # 将一批的损失相加
            pred = output.max(1, keepdim=True)[1]  # 找到概率最大的下标
            correct += pred.eq(target.view_as(pred)).sum().item()

    test_loss /= len(test_loader.dataset)
    print("\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%) \n".format(
        test_loss, correct, len(test_loader.dataset),
        100. * correct / len(test_loader.dataset)
    ))


if __name__ == '__main__':
    train_loader = torch.utils.data.DataLoader(
        torchvision.datasets.MNIST('./mnist/', train=True, download=False,
                                   transform=torchvision.transforms.Compose([
                                       torchvision.transforms.ToTensor(),
                                       torchvision.transforms.Normalize(
                                           (0.1307,), (0.3081,))
                                   ])),
        batch_size=batch_size_train, shuffle=True)
    test_loader = torch.utils.data.DataLoader(
        torchvision.datasets.MNIST('./mnist/', train=False, download=False,
                                   transform=torchvision.transforms.Compose([
                                       torchvision.transforms.ToTensor(),
                                       torchvision.transforms.Normalize(
                                           (0.1307,), (0.3081,))
                                   ])),
        batch_size=batch_size_test, shuffle=True)

    examples = enumerate(test_loader)
    batch_idx, (example_data, example_targets) = next(examples)

    network = CNN()
    model = network.to(DEVICE)
    optimizer = optim.SGD(model.parameters(), lr=learning_rate,
                          momentum=momentum)

    train_losses = []
    train_counter = []
    test_losses = []

    for epoch in range(1, EPOCHS + 1):
        train(model, DEVICE, train_loader, optimizer, epoch)
        test(model, DEVICE, test_loader)
